package com.cch.cooperation.api.common.sign;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.cch.cooperation.common.exception.BizException;
import org.redisson.api.RedissonClient;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class SignValidInterceptor implements HandlerInterceptor {

    private static final String SECRET = "symB8kVu8WdcEFqh:";
    private RedissonClient redissonClient;

    public SignValidInterceptor(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断有 NonceValid 注解
        if (handler instanceof HandlerMethod && ((HandlerMethod)handler).getMethod().isAnnotationPresent(SignValid.class)) {
            nonceValid(request);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    public void nonceValid(HttpServletRequest request) {
        String nonce = request.getHeader("nonce");
        String timestamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");
        if (StrUtil.isEmpty(nonce) || StrUtil.isEmpty(sign) || StrUtil.isEmpty(timestamp)) {
            throw new BizException("该接口无权限");
        }
        if (Long.parseLong(timestamp) < System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(10)) {
            throw new BizException("该接口无权限");
        }
        if(redissonClient.getBucket("NONCE:" + nonce).setIfExists(nonce, 15, TimeUnit.MINUTES)) {
            throw new BizException("该接口无权限");
        }
        if (!sign.equals(DigestUtil.sha256Hex(SECRET + nonce + timestamp))) {
            throw new BizException("该接口无权限");
        }
    }
}
